package packet;

import java.nio.ByteBuffer;
import java.util.HashMap;

import main.Game;

import org.apache.log4j.Logger;

import packet.player.CGLoginAsk;
  
public class PacketFactory 
{
	static Logger logger = Logger.getLogger(Game.class);
	
	private PacketFactory()
	{
		packetCreatorMap = new HashMap<Integer, Class<?>>();
	}
	
	public static PacketFactory getInstance()
	{
		if (instance == null)
		{
			synchronized(PacketFactory.class)
			{
				if (instance == null)
				{
					instance = new PacketFactory();
				}
			}
		}
		
		return instance;
	}
	
	private void registerPacketCreator(int packetID, Class<?> classPacket)
	{
		packetCreatorMap.put(packetID, classPacket);
	}
	
	public boolean initialize()
	{
		registerPacketCreator(PacketConstant.PACKET_ASK_LOGIN, CGLoginAsk.class);
		return true;
	}
	
	public Packet createPacket(byte[] data)
	{
		int    packetID = 0;
		Packet packet = null;
		
		ByteBuffer byteBuffer = ByteBuffer.allocate(data.length - 4);
		byteBuffer.put(data, 4, data.length - 4);
		byteBuffer.flip(); 
		packetID = byteBuffer.getInt();
		byteBuffer.position(0);
		
		Class<?> classPacket = packetCreatorMap.get(packetID);
		if (classPacket == null)
		{
			logger.error("Received data can not be understand.");
			return null;
		}
		
		try
		{ 
			packet = (Packet) classPacket.newInstance();
			packet.readFromBuffer(byteBuffer);
		}
		catch(Exception exception)
		{
			logger.error("Exception", exception);
			return null;
		}
		
		return packet;
	}
	
	public static PacketFactory            instance = null;
	public HashMap<Integer, Class<?>> packetCreatorMap;
}
